﻿// 功能：License管理器
// 描述：
// 作者：温伟鹏
// 日期：2010/6/8 17:06:05

using System;
using System.Runtime.InteropServices;
using System.Reflection;
using System.IO;

namespace MeizuSDK.License
{
    /// <summary>
    /// License管理器
    /// </summary>
    public class LicenseManager
    {
        #region DllImport

        [DllImport("LicenseWrapper.dll", SetLastError = true)]
        private static extern uint MyStoreVerifyWrapper([In][MarshalAs(UnmanagedType.LPWStr)]string fileName, ref VerifyContext context);
        #endregion

        #region 函数
        /// <summary>
        /// 验证License是否合法
        /// </summary>
        /// <param name="appFileName">要验证的应用程序文件路径</param>
        /// <param name="context">License信息</param>
        /// <returns>验证结果</returns>
        public static VerifyResult VerifyLicense(string appFileName, ref VerifyContext context)
        {
            uint result = (uint)VerifyResult.Unkown;

            try
            {
                result = MyStoreVerifyWrapper(appFileName, ref context);
            }
            catch (Exception) { }

            // 如果返回的结果不在已定义结果范围内，则返回未知错误
            if (!Enum.IsDefined(typeof(VerifyResult), result))
                return VerifyResult.Unkown;

            return (VerifyResult)result;
        }
        /// <summary>
        /// 验证调用此DLL的应用程序是否合法
        /// </summary>
        /// <param name="context">License信息</param>
        /// <returns>返回验证结果</returns>
        public static VerifyResult VerifySelf(ref VerifyContext context)
        {
            return VerifyLicense(GetCallingAppFilePath(), ref context);
        }
        /// <summary>
        /// 获取访问此程序集的应用程序可执行文件路径
        /// </summary>
        /// <returns></returns>
        private static string GetCallingAppFilePath()
        {
            Assembly assembly = Assembly.GetCallingAssembly();

            if (assembly == null)
                return string.Empty;

            string filePath = assembly.GetName().CodeBase;

            if (filePath.StartsWith("file://", StringComparison.InvariantCultureIgnoreCase))
            {
                filePath = filePath.Substring(7, filePath.Length - 7);
            }

            return filePath;
        }
        #endregion
    }
}
